#include <QSqlQuery>
#include <QSqlError>
#include <QVariant>
#include <QDebug>
#include "tbl_user_dao.h"

tbl_user_dao::tbl_user_dao(QSqlDatabase& db, QObject *parent) : QObject(parent),db(db)
{
    createTable();
}

bool tbl_user_dao::createTable()
{
    QString sql="CREATE TABLE 'tbl_user' ( \
            'username' TEXT NOT NULL,\
            'passwd' TEXT NOT NULL,\
            'nickname' TEXT NOT NULL,\
            'note1' TEXT,\
            'note2' TEXT,\
            PRIMARY KEY ('username'),\
            CONSTRAINT 'nickname_unique' UNIQUE ('nickname'));";
    QSqlQuery query(db);
    if(!query.exec(sql)){
        qDebug() << "创建tbl_user时发生了错误: " << query.lastError().text();
        return false;
    }
    return true;
}

bool tbl_user_dao::select(QString &username, QString &passwd, QString &msg)
{
    QString sql="select username,passwd,nickname from tbl_user where username=:username and \
            passwd=:passwd;";
    QSqlQuery query(db);
    query.prepare(sql);
    query.bindValue(":username", QVariant::fromValue(username));
    query.bindValue(":passwd", QVariant::fromValue(passwd));
    if(!query.exec()){
        msg="sql执行失败:"+query.lastError().text();
        return false;
    }
    if(!query.next()){
        msg="用户不存在或密码错误";
        return false;
    }
    msg = query.value("nickname").toString();

    return true;
}

bool tbl_user_dao::insert(QString &username, QString &passwd, QString &nickname, QString &msg)
{
    QString sql="insert into tbl_user (username,passwd,nickname)values(:username,:passwd,:nickname);";
    QSqlQuery query(db);
    query.prepare(sql);
    query.bindValue(":username", username);
    query.bindValue(":passwd", passwd);
    query.bindValue(":nickname", nickname);
    if(query.exec()){
        return true;
    }
    msg="注册失败: "+query.lastError().text();
    return false;
}
